#!/bin/bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

if [ -z "$ONE_LOCATION" ]; then
    ONE_PID=/var/run/one/oned.pid
    ONE_SCHEDPID=/var/run/one/sched.pid
    ONE_CONF=/etc/one/oned.conf
    ONE_DB=/var/lib/one/one.db
    ONE_LOG=/var/log/one/oned.log

    ONED=/usr/bin/oned
    ONE_SCHEDULER=/usr/bin/mm_sched

    LOCK_FILE=/var/lock/one/one
else
    ONE_PID=$ONE_LOCATION/var/oned.pid
    ONE_SCHEDPID=$ONE_LOCATION/var/sched.pid
    ONE_CONF=$ONE_LOCATION/etc/oned.conf
    ONE_DB=$ONE_LOCATION/var/one.db
    ONE_LOG=$ONE_LOCATION/var/oned.log

    ONED=$ONE_LOCATION/bin/oned
    ONE_SCHEDULER=$ONE_LOCATION/bin/mm_sched

    LOCK_FILE=$ONE_LOCATION/var/.lock
fi

#------------------------------------------------------------------------------
# Function that checks for running daemons and gets PORT from conf
#------------------------------------------------------------------------------
setup()
{
    PORT=$(sed -n '/^[ \t]*PORT/s/^.*PORT\s*=\s*\([0-9]\+\)\s*.*$/\1/p' \
            $ONE_CONF)

    if [ $? -ne 0 ]; then
        echo "Can not find PORT in $ONE_CONF."
        exit 1
    fi

    if [ -f $LOCK_FILE ]; then
        if [ -f  $ONE_PID ]; then
            ONEPID=`cat $ONE_PID`
            ps $ONEPID > /dev/null 2>&1
            if [ $? -eq 0 ]; then
                echo "ONE is still running (PID:$ONEPID). Please try 'one stop' first."
                exit 1
            fi
        fi
        if [ -f  $ONE_SCHEDPID ]; then
            ONESCHEDPID=`cat $ONE_SCHEDPID`
            ps $ONESCHEDPID > /dev/null 2>&1
            if [ $? -eq 0 ]; then
                echo "The scheduler is still running (PID:$ONEPID). Please try 'one stop' first."
                exit 1
            fi
        fi
        echo "Stale .lock detected. Erasing it."
        rm $LOCK_FILE
    fi
}

#------------------------------------------------------------------------------
# Function that stops the daemons
#------------------------------------------------------------------------------
stop()
{
    if [ -f $ONE_PID ]; then
        kill `cat $ONE_PID` > /dev/null 2>&1
        rm -f $ONE_PID > /dev/null 2>&1
    fi

    if [ -f $ONE_SCHEDPID ]; then
        kill `cat $ONE_SCHEDPID` > /dev/null 2>&1
        rm -f $ONE_SCHEDPID > /dev/null 2>&1
    fi
}

#------------------------------------------------------------------------------
# Function that starts the daemons
#------------------------------------------------------------------------------
start()
{
    if [ ! -x "$ONED" ]; then
        echo "Can not find $ONED."
        exit 1
    fi

    if [ ! -x "$ONE_SCHEDULER" ]; then
        echo "Can not find $ONE_SCHEDULER."
        exit 1
    fi

    if [ ! -f "$ONE_DB" ]; then
        if [ ! -f "$HOME/.one/one_auth" ]; then
            if [ -z "$ONE_AUTH" ]; then
                echo "You should have ONE_AUTH set the first time you start"
                echo "OpenNebula as it is used to set the credentials for"
                echo "the administrator user."
                exit 1
            fi
        fi
    fi

    # Backup oned.log
    if [ "$BACKUP" = "true" ];then
        [ -f "$ONE_LOG" ] && cp $ONE_LOG{,.$(date '+%Y%m%d%H%M')}
    fi

    # Start the one daemon
    $ONED -f 2>&1 &

    LASTRC=$?
    LASTPID=$!

    if [ $LASTRC -ne 0 ]; then
        echo "Error executing $ONED"
        exit 1
    else
        echo $LASTPID > $ONE_PID
    fi

    # Start the scheduler
        # The following command line arguments are supported by mm_shed:
        #  [-p port]           to connect to oned - default: 2633
        #  [-t timer]          seconds between two scheduling actions - default: 30
        #  [-m machines limit] max number of VMs managed in each scheduling action
        #                      - default: 300
        #  [-d dispatch limit] max number of VMs dispatched in each scheduling action
        #                      - default: 30
        #  [-h host dispatch]  max number of VMs dispatched to a given host in each
        #                      scheduling action - default: 1

    $ONE_SCHEDULER -p $PORT -t 30 -m 300 -d 30 -h 1&

    LASTRC=$?
    LASTPID=$!

    if [ $LASTRC -ne 0 ]; then
        echo "Error executing $ONE_SCHEDULER"
        exit 1
    else
        echo $LASTPID > $ONE_SCHEDPID
    fi

    # Wait for the daemons to warm up
    sleep 2

    STARTED="true"

    ps `cat $ONE_PID` > /dev/null 2>&1

    if [ $? -ne 0 ]; then
        echo "oned failed to start"
        STARTED="false"
    fi

    ps `cat $ONE_SCHEDPID` > /dev/null 2>&1

    if [ $? -ne 0 ]; then
        echo "scheduler failed to start"
        STARTED="false"
    fi

    if [ "$STARTED" == "false" ]; then
        stop
        exit -1
    fi
}

#------------------------------------------------------------------------------
#------------------------------------------------------------------------------

if [ "$1" = "-b" ]; then
    BACKUP=true
    shift
fi

case "$1" in
    start)
        setup
        start
        ;;
    stop)
        stop
        echo "oned and scheduler stopped"
        ;;
    *)
        echo "Usage: one [-b] {start|stop}" >&2
        echo "Options:" >&2
        echo "  -b  Backup log file." >&2
        exit 3
        ;;
esac
